//
//  HJTNetTool+WTHttp.m
//  Tourism
//
//  Created by WZH on 2018/7/3.
//  Copyright © 2018年 WZH. All rights reserved.
//

#import "HJTNetTool+WTHttp.h"

@implementation HJTNetTool (WTHttp)

+ (UIView *)keepView1{
    UIViewController *vc = UIApplication.sharedApplication.delegate.window.rootViewController;
    if ([vc isKindOfClass:[UITabBarController class]]) {
        UIViewController *vc1 = ((UITabBarController *)vc).selectedViewController;
        if ([vc1 isKindOfClass:[UINavigationController class]]) {
            return ((UINavigationController *)vc1).viewControllers.lastObject.view;
        }else if ([vc1 isKindOfClass:[UIViewController class]]) {
            return vc1.view;
        }else{
            return UIView.new;
        }
    }else if ([vc isKindOfClass:[UINavigationController class]]) {
        return ((UINavigationController *)vc).viewControllers.lastObject.view;
    }else if ([vc isKindOfClass:[UIViewController class]]) {
        return vc.view;
    }
    return UIView.new;
}


+ (void)get1:(nonnull NSString *)urlString progress:(nullable void(^)(NSProgress * _Nonnull progress))progressBlock success:(nullable void(^)(id _Nonnull responseObject))successBlock failure:(nullable void(^)(NSString  * _Nonnull errorLD))failureBlokc
{
    NSLog(@"%@",urlString);
    NSParameterAssert(urlString);
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[self keepView1] animated:YES];
    // Set the label text.
    hud.label.text = NSLocalizedString(@"Loading...", @"HUD loading title");
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    __weak typeof(self) weakSelf = self;
    [session GET:urlString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [hud hideAnimated:YES];
        __strong typeof(self) strongSelf = weakSelf;
        
        NSString *encoding = [[task response] textEncodingName];
        NSStringEncoding encod;
        NSStringEncoding sosoEncoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
        if (encoding) {
            encod = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((CFStringRef) encoding));
        } else {
            encod = NSUTF8StringEncoding;/* some sane default? */
        }
        NSString *returnString = [[NSString alloc] initWithData:responseObject encoding:encod];
        successBlock(returnString);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [hud hideAnimated:YES];
        failureBlokc(error.localizedDescription);
    }];
}

@end
